// Node.js版MongoDB初始化脚本
const { MongoClient, ObjectId } = require('mongodb');

// 连接字符串 - 根据您的环境修改
// 如果您的MongoDB需要认证，请提供用户名和密码
// 无认证时使用: mongodb://localhost:27017/
// 有认证时使用: mongodb://username:password@localhost:27017/
const uri = 'mongodb://localhost:27017/';

// 如果有用户名密码，请取消下面注释并修改
// const uri = 'mongodb://username:password@localhost:27017/';

const dbName = 'gof23-game';

// 用于测试连接的函数
async function testConnection() {
  const client = new MongoClient(uri);
  try {
    await client.connect();
    console.log('MongoDB连接成功!');
    
    // 获取可用的数据库列表
    const adminDb = client.db('admin');
    const result = await adminDb.admin().listDatabases();
    console.log('可用的数据库:');
    result.databases.forEach(db => {
      console.log(`- ${db.name}`);
    });
    
  } catch (err) {
    console.error('连接测试失败:', err);
  } finally {
    await client.close();
  }
}

async function initializeDatabase() {
  const client = new MongoClient(uri);
  
  try {
    // 连接到MongoDB
    await client.connect();
    console.log('已连接到MongoDB');
    
    // 获取数据库
    const db = client.db(dbName);
    
    // 清空现有集合
    console.log('清除现有集合...');
    await db.collection('users').drop().catch(() => console.log('users集合不存在'));
    await db.collection('progress').drop().catch(() => console.log('progress集合不存在'));
    await db.collection('patterns').drop().catch(() => console.log('patterns集合不存在'));
    await db.collection('challenges').drop().catch(() => console.log('challenges集合不存在'));
    
    // 创建示例用户
    console.log('创建示例用户...');
    const userId = new ObjectId("5d7a514b5d2c12c7449be042");
    await db.collection('users').insertOne({
      name: "测试用户",
      email: "test@example.com",
      password: "$2a$10$XQDpG7aKOKrOKh5OjQZkiO7UMcKIJDqDFsQqJ6nFf2ZTINrxMEE6G", // "password"
      date: new Date(),
      _id: userId
    });
    
    // 初始化设计模式
    console.log('初始化设计模式...');
    const patternCategories = [
      {
        name: "创建型模式",
        patterns: [
          { name: "单例模式", key: "singleton", level: "初级" },
          { name: "工厂方法模式", key: "factory_method", level: "初级" },
          { name: "抽象工厂模式", key: "abstract_factory", level: "中级" },
          { name: "建造者模式", key: "builder", level: "中级" },
          { name: "原型模式", key: "prototype", level: "初级" }
        ]
      },
      {
        name: "结构型模式",
        patterns: [
          { name: "适配器模式", key: "adapter", level: "初级" },
          { name: "桥接模式", key: "bridge", level: "中级" },
          { name: "组合模式", key: "composite", level: "中级" },
          { name: "装饰模式", key: "decorator", level: "中级" },
          { name: "外观模式", key: "facade", level: "初级" },
          { name: "享元模式", key: "flyweight", level: "高级" },
          { name: "代理模式", key: "proxy", level: "初级" }
        ]
      },
      {
        name: "行为型模式",
        patterns: [
          { name: "责任链模式", key: "chain_of_responsibility", level: "中级" },
          { name: "命令模式", key: "command", level: "初级" },
          { name: "解释器模式", key: "interpreter", level: "高级" },
          { name: "迭代器模式", key: "iterator", level: "中级" },
          { name: "中介者模式", key: "mediator", level: "中级" },
          { name: "备忘录模式", key: "memento", level: "中级" },
          { name: "观察者模式", key: "observer", level: "初级" },
          { name: "状态模式", key: "state", level: "中级" },
          { name: "策略模式", key: "strategy", level: "初级" },
          { name: "模板方法模式", key: "template_method", level: "初级" },
          { name: "访问者模式", key: "visitor", level: "高级" }
        ]
      }
    ];

    // 转换为平面模式列表
    let patterns = [];
    for (const category of patternCategories) {
      for (const pattern of category.patterns) {
        patterns.push({
          name: pattern.name,
          key: pattern.key,
          category: category.name,
          level: pattern.level,
          description: `${pattern.name}的基本描述`,
          codeExample: `// ${pattern.name} 示例代码`,
          realWorldUsage: `${pattern.name}的实际应用场景`
        });
      }
    }
    
    // 插入所有模式
    const patternsResult = await db.collection('patterns').insertMany(patterns);
    console.log(`已添加 ${patternsResult.insertedCount} 个设计模式`);
    
    // 初始化每个模式的挑战
    console.log('初始化挑战...');
    let challenges = [];
    patterns.forEach(pattern => {
      const patternChallenges = [
        {
          patternKey: pattern.key,
          title: `${pattern.name} - 基础理解`,
          description: `展示你对${pattern.name}基本概念的理解`,
          type: "quiz",
          difficulty: "easy",
          points: 10,
          content: {
            question: `${pattern.name}的主要目的是什么？`,
            options: [
              `实现${pattern.name}的核心功能`,
              `提高代码的复用性`,
              `降低系统各部分的耦合度`,
              `以上都是`
            ],
            correctAnswer: 3
          }
        },
        {
          patternKey: pattern.key,
          title: `${pattern.name} - 代码实现`,
          description: `完成${pattern.name}的基本代码实现`,
          type: "coding",
          difficulty: "medium",
          points: 20,
          content: {
            instructions: `请实现一个简单的${pattern.name}示例`,
            initialCode: `// 在这里实现${pattern.name}`,
            testCases: [
              {
                input: "test",
                expectedOutput: "success"
              }
            ]
          }
        },
        {
          patternKey: pattern.key,
          title: `${pattern.name} - 实际应用`,
          description: `在实际场景中应用${pattern.name}`,
          type: "project",
          difficulty: "hard",
          points: 30,
          content: {
            requirements: `创建一个使用${pattern.name}的小项目`,
            deliverables: ["源代码", "文档说明", "单元测试"]
          }
        }
      ];
      
      challenges = challenges.concat(patternChallenges);
    });

    const challengesResult = await db.collection('challenges').insertMany(challenges);
    console.log(`已添加 ${challengesResult.insertedCount} 个挑战`);
    
    // 初始化进度记录为零进度
    console.log('初始化用户进度...');
    let progressRecords = [];
    
    patterns.forEach(pattern => {
      progressRecords.push({
        userId: userId,
        patternKey: pattern.key,
        completedChallenges: [],
        currentScore: 0,
        maxScore: 60, // 每个模式挑战的总分数
        isComplete: false,
        lastUpdated: new Date()
      });
    });

    const progressResult = await db.collection('progress').insertMany(progressRecords);
    console.log(`已添加 ${progressResult.insertedCount} 个进度记录`);

    console.log('数据库初始化完成！');
    
  } finally {
    await client.close();
    console.log('MongoDB连接已关闭');
  }
}

// 先测试连接
console.log('测试MongoDB连接...');
testConnection()
  .then(() => {
    console.log('准备初始化数据库...');
    return initializeDatabase();
  })
  .catch(err => {
    console.error('初始化过程出错:', err);
  }); 